package com.springboot.jdk.nio;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * FileChannel Demo2 案例
 *
 * @author: zr
 * @date: 2021-10-19
 */
public class FileChannelDemo2 {

    public static void main(String[] args) throws IOException {
        String path = "F:\\develop\\channel\\hello.txt";

        File file = new File(path);
        File fileParent = file.getParentFile();
        if (!fileParent.exists()) {
            fileParent.mkdirs();
        }
        file.createNewFile();

        // 构造一个传统的文件输出流
        FileOutputStream fileOutputStream = new FileOutputStream(path);

        // 通过文件输出流获取到对应的FileChannel, 已NIO的方式来写文件
        FileChannel channel = fileOutputStream.getChannel();

        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                // 构建一个 ByteBuffer 缓冲区
                ByteBuffer wrap = ByteBuffer.wrap("hello world".getBytes());

                // 通过channel将 Buffer 里面的数据写入到磁盘文件里面
                try {
                    channel.write(wrap);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}
